package com.hairline.hairlinemarket.config;


import com.hairline.hairlinemarket.shiro.WdAuthenticator;
import com.hairline.hairlinemarket.shiro.WdRealm;
import com.hairline.hairlinemarket.shiro.WdSessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;

/**
 * Author:杨小凯
 * Date:2023-04-21 15:30
 * Description:<描述>
 */
@Configuration
public class ShiroConfiguration {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        // ShiroFilter
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setLoginUrl("/admin/auth/nologin");
        // ShiroFilter里提供的FilterChain
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/admin/auth/login", "anon"); // /admin/auth/login → anon
        filterChainDefinitionMap.put("/admin/auth/info", "anon");
        filterChainDefinitionMap.put("/admin/auth/nologin", "anon");

        filterChainDefinitionMap.put("/admin/**", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        //DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(WdRealm wdRealm,
                                                     WdSessionManager wdSessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //securityManager.setAuthenticator(); // Shiro有提供默认值 → 你可以不提供的
        //securityManager.setAuthorizer(); // Shiro有提供默认值 → 你可以不提供的
        //securityManager.setRealms(Arrays.asList(new WdRealm()));
        // 想要提供一个自定义的认证器
        //securityManager.setAuthenticator(wdAuthenticator);
        securityManager.setRealms(Arrays.asList(wdRealm));
        securityManager.setSessionManager(wdSessionManager);
        return securityManager;
    }

    // 用到AspectJ → 使用注解的方式，将权限和url绑定起来
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
